<template>
  <div>
    <div
      style="width: 400px;height: calc(100vh - 50px);border-left: 1px solid lightgray;display: inline-block;position: fixed;right: 0;bottom: 0;">
      <router-view style="width: 100%;height: calc(100vh - 50px);"></router-view>
    </div>
    <div style='max-width: 500px'>
      <q-form @reset='onReset' class='q-gutter-md'>
        <div v-for='(item, index) in updateCarArr' :key='index'>
          <q-input filled v-if='item.type == "num"' type='number' v-model='item.value' :label='item.Rea_label'
            :rules="[val => (val && val.length <= item.length) || '必填项且不可超过' + item.length + '个字符']" />

          <q-input filled v-else-if='item.type == "char0"' v-model='item.value' :label='item.Rea_label' disable
            :rules="[val => (val && val.length <= item.length) || '必填项且不可超过' + item.length + '个字符']" />

          <div v-else-if=yeso(item.type) @click='touch(index)'>
            <q-select :disable='item.type == "list10" ? true : false' filled v-model='item.value' use-input
              hide-dropdown-icon hide-selected fill-input input-debounce='0' :options=item.arr @filter='filterFn'
              @update:model-value='setModel' :label='item.Rea_label' style='width: 500px; padding-bottom: 32px'>
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class='text-grey'>
                    No results
                  </q-item-section>
                </q-item>
              </template>
            </q-select>
          </div>
          <div v-else-if='item.type == "dic"'>
          </div>

          <div v-else-if='item.type == "image"'
            style="width: 500px;padding: 10px 10px;border-radius: 5px;border: 1px solid lightgray;margin-bottom: 32px;">
            <div style="font-size: 12px;color: dimgray;margin-bottom: 15px;">{{ item.Rea_label }}</div>
            <div title="点击查看大图"
              style="width: 300px;height: 200px;border-radius: 5px;background-position: center;background-size: contain;border: 1px solid lightgray;display: inline-block;background-repeat: no-repeat;padding-left: 150px;padding-top: 100px;"
              :style="{
                backgroundImage: 'url(' + item.value + ')'
              }" @click="() => {
                if (item.value == '' || item.value == null) return
                window.open(item.value, '_blank')
              }">
              <div v-if="item.value == ''"
                style="display: inline-block;font-size: 14px;transform: translate(-50%,-50%);">
                无图片</div>
            </div>
            <div style="width: 160px;display: inline-block;height: 200px;float: right;">
              <div v-if="item['status'] == 1" style="font-size: 14px;margin-bottom: 20px;color: rgb(0,120,215);">
                正在上传
              </div>
              <div v-if="item['status'] == 2" style="font-size: 14px;margin-bottom: 20px;color: green;">
                上传成功
              </div>
              <div v-if="item['status'] == 3" style="font-size: 14px;margin-bottom: 20px;color: red;">
                上传失败
              </div>
              <q-btn @click="deleteImage(index); item['status'] = undefined"
                v-if="!(item.value == '' || item.value == null)"
                style="display: inline-block;width: 100%;margin-bottom: 20px;" color="white" text-color="black"
                label="删除图片" />
              <q-btn @click="selectSingleImage(index)" v-if="!(item.value == '' || item.value == null)"
                style="display: inline-block;width: 100%;margin-bottom: 20px;" color="white" text-color="black"
                label="修改图片" />
              <q-btn @click="selectSingleImage(index)" v-if="item.value == '' || item.value == null"
                style="display: inline-block;width: 100%;margin-bottom: 20px;" color="white" text-color="black"
                label="选择图片" />
            </div>
          </div>

          <q-input filled v-else v-model='item.value' :label='item.Rea_label'
            :rules="[val => (val && val.length <= item.length) || '必填项且不可超过' + item.length + '个字符']" />

        </div>
        <div v-if='entityCode == "701" && operateEvent !== "704"'>
          <div class='col-2 input-label'>
            图片
          </div>
          <div class='col-8' v-for='item in serveIdArr'>
            <img :src='getImageURL1(item)' alt='车'>
          </div>
        </div>
        <div v-for='(item, index) in dicArray' :key='index'>
          <div @click='searchDic(item)'>
            <q-select ref='fix' filled v-model="item.value" :label="item.Rea_label" use-input input-debounce="0"
              :options="dicOptions" style="width: 500px" @update:model-value='getNumber(item, index)'>
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey">
                    No results
                  </q-item-section>
                </q-item>
              </template>
            </q-select>
          </div>
        </div>

        <div>
          <q-btn :label='carDate.operateEventName' type='button' color='primary' @click='updateInfo' />
          <q-btn label='重置' type='reset' color='primary' flat class='q-ml-sm' />
        </div>
      </q-form>
    </div>
  </div>
</template>
<script lang='ts'>
import { useRouter, useRoute } from 'vue-router';
import { onMounted, ref, reactive, defineComponent, onBeforeUnmount } from 'vue';
import { getRequest, postRequest, postRequest1, getRequest1 } from 'src/components/functions';
import { columnSelection, TableValue } from 'components/models';
import { useQuasar, Notify } from 'quasar';
import { useStore } from 'src/store';
import { api } from 'boot/axios';


let stringOptions = [];

export default defineComponent({
  name: 'Add.vue',
  computed: {
    window() {
      return window
    }
  },
  setup(props, { emit }) {
    const model = ref(null);
    const options = ref(stringOptions);
    let totalColumns: any = [];
    let router = useRouter();
    let rote = useRoute();
    const store = useStore();
    const userData = store.state.sphinx.userData;
    const ChainData = store.state.sphinx.Chain;
    let prevOpt = store.state.sphinx.prevOpt;
    let serverGeneralStat = store.state.sphinx.serverGeneralStat;
    let prevOptEntity = store.state.sphinx.currentOptEntity;
    let prevUrl = store.state.sphinx.prevUrl;
    let updateCarArr = ref<TableValue[] | undefined>();
    let listRes;
    let entityCode = ref(rote.query.entityCode);
    let childCode = ref(rote.query.childCode);
    let toEntityCode1 = '';
    let toEntityType1 = '';
    let updataDataUrl = ref('');
    const carDate = useStore().state.sphinx.CarMessage;
    let operateEvent = ref(rote.query.operateEvent);
    let operateEventName = ref(rote.query.operateEventName);
    const $q = useQuasar();
    let loadingTimer;
    // let searchFrameArr = ref([]);
    let QueryBarUrl = ref<string>('');
    let times = ref(0);
    let tempArr = [];
    let theirEventCodeTemp;
    let length = 0
    let tempListCode = '';
    let dicArray = reactive([])
    let fix = ref()
    console.log('555', ChainData)

    //设置表单内绑定的初始值
    function setInitValue() {
      if (updateCarArr.value !== undefined) {

        if (length === 0) {
          for (let i = 0; i < updateCarArr.value.length; i++) {

            if (updateCarArr.value[i].value === "") {
              updateCarArr.value[i].value = carDate[updateCarArr.value[i].label];
            }

          }
        }

      }
      for (let i = 0; i < updateCarArr.value.length; i++) {
        tempArr.push(updateCarArr.value[i].value)
      }
    }

    function yeso(item) {
      if (item.substring(0, 4) == 'list') {
        return true;
      } else {
        return false;
      }
    }

    //获取修改属性名
    function getAddClomn() {
      let sceneCode = ''
      let requestSceneBody = [
        {
          "entityCode": '101',
          "codeName": '',
          "entityType": '01',
          "typeName": '',
          "eventCode": null,
          "eventName": null,
          "propertyEnglish": null,
          "propertyChinese": null,
          "propertyValue": null,
          "propertyCondition": null,
          "companyId": userData.companyId
        },
        {
          "entityCode": '102',
          "codeName": '',
          "entityType": '02',
          "typeName": '',
          "eventCode": null,
          "eventName": null,
          "propertyEnglish": 'roleType',
          "propertyChinese": null,
          "propertyValue": userData.roleType,
          "propertyCondition": null,
          "companyId": userData.companyId
        }];
      api.post('/channel/channel/getSceneCode', requestSceneBody).then(res => {
        if (res.status == 200) {
          sceneCode = res.data.data;
          let postData = {
            entityCode: entityCode.value,
            entityType: childCode.value,
            sceneCode: sceneCode,
            objectCodeType: operateEvent.value,
            companyId: userData.companyId
          };
          postRequest('channel/channel/instre', postData, callback);
        }
      })
    }

    let t: TableValue[] = [];
    //获取属性名的回调函数
    async function callback(data: any[]) {
      totalColumns = data;
      console.log("xpa789,data", data);
      let n: TableValue[] = [];
      if (data) {
        let temp = []
        console.log("carDate", prevOpt)
        //let url = "/transaction/sub/fetchChannelRoute??relationFlag=1&entityCode="+prevOpt.entityCode+"&entityType="+prevOpt.entityType+"&otherEventCode="+theirEventCodeTemp;
        let url = "/transaction/sub/fetchChannelRoute?relationFlag=1&entityCode=" + prevOptEntity.entityCode + "&entityType=" + prevOptEntity.childCode + "&otherEventCode=" + theirEventCodeTemp + "&otherEntityCode=" + entityCode.value + "&otherEntityType=" + childCode.value;
        console.log('list查询条件赋值', url)
        await getRequest(url, (data) => {
          length = data.length
          //匹配数据
          data.forEach(z => {
            for (let key in prevOpt) {
              if (z.propertyEnglish === key) {
                temp.push({ key: z.otherPropertyEnglish, value: prevOpt[key] })
              }
            }

          })
        })

        data.forEach((item, index) => {
          let invalue = ''
          temp.forEach(x => {
            if (item.propertyCode === x.key) {
              console.log(x.value)
              console.log("匹配上的列名", x.key)
              invalue = x.value
            }
          })
          console.log("list匹配上的参数", invalue)
          if (item.propertyType.indexOf('list') != -1) {
            console.log("xpa780")
            if (serverGeneralStat) {
              console.log('item.propertyType', item.propertyType)
              console.log("getProperty", item)
              postRequest('/channel/channel/getPropertyInterface',
                { entityCode: entityCode.value, entityType: childCode.value, eventCode: operateEvent.value, propertyCode: item.propertyCode },
                (resDataIn) => {
                  let interfaceEnglish = resDataIn.data.interfaceEnglish;
                  let urls = interfaceEnglish.substring(interfaceEnglish.indexOf('/'), interfaceEnglish.length);

                  let strings1 = urls.split('?')[1].split('&');
                  let toEntityCode, toEntityType;
                  strings1.forEach(x => {
                    let strings = x.split('=');
                    if (strings[0] === 'entityCode') {
                      toEntityCode = strings[1];
                      toEntityCode1 = toEntityCode;
                    } else if (strings[0] === 'entityType') {
                      toEntityType = strings[1];
                      toEntityType1 = toEntityType;
                    }
                  })

                  let reqUrl = "/transaction/sub/fetchChannelRoute?relationFlag=3&entityCode=" + prevOptEntity.entityCode + "&entityType=" + prevOptEntity.childCode + "&otherEventCode=" + theirEventCodeTemp + "&otherEntityCode=" + toEntityCode + "&otherEntityType=" + toEntityType;
                  console.log("xpa098,reqUrl", reqUrl);
                  getRequest(reqUrl, (resInDatas) => {
                    resInDatas.forEach(x => {
                      urls += '&' + x.propertyEnglish + '=' + carDate[x.propertyEnglish];
                    })
                    console.log('list下拉框请求地址', urls);
                    getRequest(urls, (data) => {
                      if (data !== undefined && data.length > 0) {
                        let arrs = [];
                        let strings = urls.split('?');

                        getRequest("/transaction/sub/getEntityPropertyList?" + strings[1], (propertyListData) => {
                          let listName = propertyListData[0].listName;
                          tempListCode = propertyListData[0].listCode;
                          console.log('listName', listName)

                          data.forEach(x => {
                            let x1 = x[listName];
                            if (x1 !== '') {
                              arrs.push({ item: item, label: x1, value: x1, selections: undefined, temp: x, toEntityCode: toEntityCode, toEntityType: toEntityType });
                            }

                          });
                          console.log('初始主体赋值', arrs)
                          mouseover(item, (res, selectItems, propertyCode, selectionsData) => {
                            let temp = updateCarArr.value;
                            temp.push(
                              {
                                Rea_label: item.propertyName,
                                value: invalue,
                                label: item.propertyCode,
                                length: item.propertyLength,
                                type: item.propertyType,
                                time: false,
                                arr: arrs,
                                arrTemp: arrs,
                                selected: '',
                                selectionsData: selectionsData,
                                item: selectItems
                              }
                            );
                            updateCarArr.value = temp;
                          });
                        })
                      }
                    })


                  })



                })

            } else {
              console.log("xpa123456,updateCarArr", updateCarArr.value);
              mouseover(item, (res, selectItems, propertyCode, selectionsData) => {
                let temp = updateCarArr.value;
                temp.push(
                  {
                    Rea_label: item.propertyName,
                    value: invalue,
                    label: item.propertyCode,
                    length: item.propertyLength,
                    type: item.propertyType,
                    time: false,
                    arr: complieSelections(selectItems, item, propertyCode),
                    arrTemp: complieSelections(selectItems, item, propertyCode),
                    selected: '',
                    selectionsData: selectionsData,
                    item: selectItems
                  }
                );
                updateCarArr.value = temp;
              });
            }
          } else {
            n.push(
              {
                Rea_label: item?.propertyName,
                value: invalue,
                label: item?.propertyCode,
                length: item?.propertyLength,
                type: item?.propertyType,
                time: false,
                arr: [],
                arrTemp: [],
                selected: '',
                selectionsData: null,
                item: undefined
              }
            );
            setTimeout(() => {
              setInitValue();
            }, 300)
          }
          if (item.propertyType == "dic") {
            dicArray.push({
              Rea_label: item.propertyName,
              value: '',
              label: item.propertyCode,
              code: '',
              length: item.propertyLength,
              type: item.propertyType,
            })
          }
        });
      }
      updateCarArr.value = n;
    }

    function complieSelections(selectItems: string[], item: any, propertyCode: string): columnSelection[] {

      let selection: columnSelection[] = [];

      selectItems.forEach((x: any) => {
        const selectItem: columnSelection = {
          label: x[propertyCode],
          value: x[propertyCode],
          item: item,
          selections: x.companyType
        };
        selection.push(selectItem);
      });


      return selection;
    }

    function getPropertysByPropertyType(propertyType: string): any {
      let propertyCode = undefined;
      const s = propertyType.substring(0, propertyType.length - 1) + '0';
      console.log("属性类型propertyType：", s)//list10
      totalColumns.forEach((x: any) => {
        if (x.propertyType == s) {
          if (propertyCode === undefined) {
            propertyCode = x.propertyCode;
          }
        }
      });
      console.log("属性代码propertyCode：", propertyCode)//roleType
      return propertyCode;
    }

    function getIndexByPropertyCode(propertyCode: string, companyType: string, realValue: string) {
      const value = updateCarArr.value;
      console.log(value)
      value.forEach((x: any, y: number) => {
        if (x.label == propertyCode) {
          if (x.item !== undefined) {
            x.item.forEach((z: any) => {
              if (z.roleName == realValue) {
                x.value = z.roleType
              }
            });
          }
        }
      });
      updateCarArr.value = value;
    }

    //获取修改主体的接口
    function getAdddataUrl() {
      let data = {
        entityCode: entityCode.value,
        entityType: childCode.value,
        theirEventCode: operateEvent.value
      };
      postRequest('/channel/channel/getInterface', data, res => {
        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
        let url = res.data?.interfaceEnglish;
        theirEventCodeTemp = data.theirEventCode;
        getAddClomn();//获取需要表单头信息，显示
        updataDataUrl.value = url.substr(url.indexOf('/') + 1);
      });
    }

    //提交修改表单
    function updateInfo() {
      console.log("updateCarArr.value", updateCarArr.value);
      let entityCode0 = entityCode.value;
      let entityType0 = childCode.value;
      let operateEvent0 = operateEvent.value;

      let data = {
        entityCode: entityCode.value,
        entityType: childCode.value,
        uuid: '',
        eventCode: operateEvent.value,
        eventName: operateEventName.value,
        companyId: userData.companyId,
        userId: userData.userId,
        userName: userData.userName,

        carNo: '',
        isRoot: "1",
        scene: ChainData,
      };
      //data = Object.assign(data, store.state.sphinx.selectedItemData[store.state.sphinx.selectedItemData.length - 1]);
      // console.log("carNo",data.carNo);
      console.log("operateEventName xpa", operateEventName.value);
      console.log("scene: ChainData", ChainData);
      console.log("xpa data ", data);

      if (updateCarArr.value !== undefined) {
        for (let i = 0; i < updateCarArr.value.length; i++) {
          let key = updateCarArr.value[i].label;
          let val: any;
          if (typeof (updateCarArr.value[i].value) !== 'object') {
            val = updateCarArr.value[i].value;
            data[key] = val;
          } else {
            let obj: any = updateCarArr.value[i].value;
            if (updateCarArr.value[i].value == null) {
              val = updateCarArr.value[i].value;
              data[key] = val;
            } else {
              if (obj.hasOwnProperty('value')) {
                val = obj.value;
              }
            }
            data[key] = val;
          }
        }
        data.uuid = carDate.uuid;
        // console.log("data.uuid",data.uuid);
        // console.log("data.eventCode",data.eventCode);
        data.carNo = carDate.carNo;
        // console.log("carNo",data.carNo);
        // if(entityCode.value == "301" || entityCode.value.length == 5 || data.eventCode == "004" ){

        // }
      }
      dicArray.forEach((item, index, array) => {
        data[item.label] = item.code
      })


      if (entityCode0 === "602" && entityType0 === "21" && operateEvent0 === "002") {
        data['addFlag'] = '0000000001000000'
      }


      if (entityCode0 === "250" && entityType0 === "10" && operateEvent0 === "513") {

        console.log("采购计划逻辑data", data);
        getRequest1("BusEntityEventServlet", (res) => {
          // if (res) {
          emit('rightInfo', {
            opName: 'refreshRight',
          })
          $q.loading.show({
            message: res
          });
          loadingTimer = setTimeout(() => {
            $q.loading.hide();
            loadingTimer = void 0;
            void router.push('/list?' + prevUrl);
            //window.history.back()
          }, 1000);
          // }
        }, data);


      } else {

        postRequest(updataDataUrl.value, data, (res) => {
          // if (res) {

          emit('rightInfo', {
            opName: 'refreshRight',
          })

          $q.loading.show({
            message: res
          });
          loadingTimer = setTimeout(() => {
            $q.loading.hide();
            loadingTimer = void 0;
            void router.push('/list?' + prevUrl);
            //window.history.back()
          }, 1000);
          // }
        });

      }





    }

    //重置表单
    function onreset() {
    }

    onBeforeUnmount(() => {
      if (loadingTimer !== void 0) {
        clearTimeout(loadingTimer);
        $q.loading.hide();
      }
    });

    // 点击获取主体属性列表框
    function mouseover(item, fun) {
      console.log("xpa mouseover");
      let getListInterface = 'channel/channel/getPropertyInterface';
      //获取属性list的接口
      let resData = {
        entityCode: entityCode.value,
        entityType: childCode.value,
        eventCode: operateEvent.value,
        propertyCode: item.propertyCode
      };

      postRequest(getListInterface, resData, res => {
        if (res.data.interfaceEnglish.indexOf('transaction/sub/getEntityTable') != -1) {
          serverGeneralStat = true
        }
        let n = [];
        let interfaceEnglish = res.data.interfaceEnglish;
        if (res.data !== null && interfaceEnglish !== undefined) {
          QueryBarUrl.value = interfaceEnglish;
          let selectionsData = res.data;
          if (res.status == 'SUCCESS') {
            let url = res.data.interfaceEnglish;
            let requestType = url.substr(0, url.indexOf('/'));
            let formUrl = url.substr(url.indexOf('/') + 1);
            if (requestType.indexOf('get') !== -1) {
              getRequest(formUrl, analyzeCallback);
            } else {
              postRequest(formUrl, { companyId: userData.companyId }, analyzeCallback);
            }

            function analyzeCallback(res) {
              console.log("xpa res", res);

              listRes = res;

              for (let i = 0; i < res.length; i++) {
                let e = item.propertyCode;
                n.push(res[i][e]);
              }
              fun(n, res, item.propertyCode, selectionsData);
              setInitValue();
            }

          }
        }

      });
    }
    let serveIdArr = ref([]);
    function getImageId() {
      const reqParams = {
        //@ts-ignore
        serveNo: carDate.serveNo
      }
      getRequest('file/file/downloadByEntityId', (res) => {
        serveIdArr.value = res;
      }, reqParams)
    }

    function getImageURL1(item) {
      return `${process.env.api}file/file/downloadByEntity?fileEntityId=${item}`;
    }

    onMounted(() => {
      getImageId();

      getAdddataUrl();
    });

    let indexTemp;
    let item = undefined;

    function filterFn(val, update, abort) {
      setTimeout(() => {
        const tableValue = updateCarArr.value[indexTemp];
        let selectionsData = tableValue.selectionsData;
        if (item === undefined) {
          console.log("tableValue", tableValue)
          item = tableValue.arr[0].item;
          console.log("tableValue0", item)
        }
        const arrTemp = tableValue.arrTemp;
        update(() => {
          const needle = val.toLocaleLowerCase();

          tableValue.arr = arrTemp.filter(v => {
            if (!!needle) {
              return v?.label?.toLocaleLowerCase().indexOf(needle) > -1
            } else {
              return false;
            }

          });
          if (tableValue.arr.length == 0) {
            let propertyCode1 = selectionsData.propertyCode;
            let reqData = {};
            reqData[propertyCode1] = val;
            if (serverGeneralStat) {
              postRequest('/channel/channel/getPropertyInterface',
                { entityCode: entityCode.value, entityType: childCode.value, eventCode: operateEvent.value, propertyCode: item.propertyCode },
                async (resDataIn) => {
                  let interfaceEnglish = resDataIn.data.interfaceEnglish;
                  let urls = interfaceEnglish.substring(interfaceEnglish.indexOf('/'), interfaceEnglish.length);
                  console.log('下拉框请求地址', urls)
                  let strings1 = urls.split('?')[1].split('&');
                  let toEntityCode, toEntityType;
                  strings1.forEach(x => {
                    let strings = x.split('=');
                    if (strings[0] === 'entityCode') {
                      toEntityCode = strings[1]
                      toEntityCode1 = toEntityCode;
                    } else if (strings[0] === 'entityType') {
                      toEntityType = strings[1]
                      toEntityType1 = toEntityType;
                    }
                  })

                  //跨页面路由
                  let bodyInfo = localStorage.getItem('currentBody')
                  if (bodyInfo != null) {
                    bodyInfo = JSON.parse(bodyInfo)
                    bodyInfo['eventCode'] = operateEvent.value
                    // let opr = await or.tableRowClick(bodyInfo, {
                    //   otherEntityCode: toEntityCode,
                    //   otherEntityType: toEntityType,
                    // })
                    // console.log(opr)
                    // router.push(opr)
                    emit('rightInfo', {
                      opName: 'showAndRefreshRight',
                      bodyInfo: bodyInfo,
                      otherBodyInfo: {
                        otherEntityCode: toEntityCode,
                        otherEntityType: toEntityType,
                      }
                    })
                  }
                  //

                  //本页面路由
                  let reqUrl = "/transaction/sub/fetchChannelRoute?relationFlag=3&entityCode=" + entityCode.value + "&entityType=" + childCode.value + "&otherEventCode=" + theirEventCodeTemp + "&otherEntityCode=" + toEntityCode + "&otherEntityType=" + toEntityType;
                  getRequest(reqUrl, (resInDatas) => {
                    resInDatas.forEach(x => {
                      //x.propertyEnglish应该是otherpropertyEnglish?
                      updateCarArr.value.forEach(y => {
                        if (y.label === x.propertyEnglish) {
                          urls += '&' + x.otherPropertyEnglish + '=' + y.value;
                        }
                      })

                    })

                    if (entityCode.value == '602' && childCode.value == '21') {

                      urls += '&' + 'field3' + '=' + userData.userId;

                    }

                    console.log('list下拉框请求地址', urls);
                    getRequest(urls, (data) => {
                      if (data !== undefined && data.length > 0) {
                        let arrs = [];
                        let strings = urls.split('?');

                        getRequest("/transaction/sub/getEntityPropertyList?" + strings[1], (propertyListData) => {
                          let listName = propertyListData[0].listName;
                          tempListCode = propertyListData[0].listCode;
                          console.log('listName_xpa', listName);
                          data.forEach(x => {
                            let x1 = x[listName];
                            if (x1 !== '') {
                              console.log("CCXXYY", x)
                              arrs.push({ item: item, label: x1, value: x1, selections: undefined, temp: x, toEntityCode: toEntityCode, toEntityType: toEntityType });
                            }

                          });
                          tableValue.arr = arrs;
                          tableValue.arrTemp = arrs;
                        })
                      }
                    })


                  })




                })

            } else {
              postRequest(selectionsData.interfaceEnglish, reqData, (data) => {
                if (data !== undefined && data.length > 0) {
                  let arrs = [];
                  data.forEach(x => {
                    let x1 = x[propertyCode1];

                    arrs.push({ item: item, label: x1, value: x1, selections: undefined });
                  });
                  tableValue.arr = arrs;
                  console.log("004", arrs)
                  tableValue.arrTemp = arrs;
                }
              });
            }

          }
        });
      }, 300);


    }



    function touch(index) {
      indexTemp = index;
      item = undefined;
    }
    //list点击事件
    function setModel(val) {
      console.log('选中值', val)
      console.log('选中值——xpa')
      let propertyType1 = val.item.propertyType;
      let propertyType0;
      console.log('点击事件propertyType1:', propertyType1)
      if (propertyType1 === 'list11') {
        propertyType0 = 'list10';
      }
      if (propertyType1 === 'list21') {
        propertyType0 = 'list20';
      }
      if (propertyType1 === 'list31') {
        propertyType0 = 'list30';
      }
      console.log('点击事件propertyType0:', propertyType0)
      const propertysByPropertyType = getPropertysByPropertyType(val.item.propertyType);
      console.log('点击事件propertysByPropertyType:', propertysByPropertyType)

      //向平安增加20221025
      let i1;
      for (let i = 0; i < listRes.length; i++) {

        // if((listRes[i].propertyCode) == val){

        i1 = i;

        //  }

      }


      getIndexByPropertyCode(propertysByPropertyType, val.selections, val.value);



      model.value = val;
      model.value = val;
      console.log("xpa135 val", val.item);
      //暂时写死
      let toEntityCode2 = '301';
      let toEntityType2 = '19';

      if (serverGeneralStat) {
        let url = "/transaction/sub/fetchChannelRoute?relationFlag=4&entityCode=" + toEntityCode2 + "&entityType=" + toEntityType2 + "&otherEventCode=" + theirEventCodeTemp + "&otherEntityCode=" + entityCode.value + "&otherEntityType=" + childCode.value;
        getRequest(url, (data) => {
          console.log('获取链匹配关系', data);
          console.log('页面输入框对象updateCarArr', updateCarArr);
          console.log("页面未填充数据", val.temp)
          data.forEach(z => {
            updateCarArr.value.forEach(x => {
              for (let item in val.temp) {

                if (x.label === item && x.label === z.otherPropertyEnglish) {

                  console.log("x.label:", x.label);
                  console.log("item:", item);

                  x.value = val.temp[item]
                }

              }

            })
          })
          console.log('tempListCode', tempListCode)
          updateCarArr.value.forEach(x => {
            // if (x.type === 'list10') {
            //   x.value = val.temp[tempListCode]
            // }
            if (x.type === propertyType0) {
              console.log("点击事件x.value", x.value)
              x.value = val.temp[tempListCode]
            }
          })

        })
      }
    }

    function onReset() {
      for (let i = 0; i < updateCarArr.value.length; i++) {
        updateCarArr.value[i].value = tempArr[i];
      }
    }
    function getNumber(item, index) {
      let reqData = {
        entityCode: entityCode.value,
        entityType: childCode.value,
        propertyEnglish: item.label
      }
      getRequest('/channel/channel/queryEntityPropertyDic', (res) => {
        res.forEach((i, index1, array) => {
          if (i.dicName == item.value) {
            dicArray[index].code = i.dicCode;
          }
        })
        // console.log(dicArray);
      }, reqData)
    }
    let dicOptions = ref([])
    function searchDic(item) {
      stringOptions = []
      let reqData = {
        entityCode: entityCode.value,
        entityType: childCode.value,
        propertyEnglish: item.label
      }
      getRequest('/channel/channel/queryEntityPropertyDic', (res) => {
        res.forEach((item, index, array) => {
          stringOptions.push(item.dicName)
        })

        if (dicOptions.value.length === 0) {
          if (fix?.value?.hidePopup) {
            fix?.value?.hidePopup()
            setTimeout(() => {
              fix?.value?.showPopup()

            }, 100)
          }

        }
        dicOptions.value = stringOptions
      }, reqData)
    }

    function deleteImage(index) {
      updateCarArr.value[index].value = ''
    }

    function selectFile() {
      return new Promise((resolve, reject) => {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = 'image/*';

        input.addEventListener('change', (e) => {
          const file = e.target['files'][0];
          if (file) {
            if (file.type.startsWith('image/')) {
              resolve(file);
            } else {
              reject(new Error('请选择一个图片文件'));
            }
          } else {
            resolve(false);
          }
        });

        input.addEventListener('click', () => {
          setTimeout(() => input.remove(), 0); // 选择文件后立即移除input元素
        });

        input.click();
      });
    }

    async function selectSingleImage(index) {
      let re = undefined
      try {
        re = await selectFile()
      } catch (error) {
        updateCarArr.value[index]['status'] = 3
        return
      }
      if (re == undefined) {
        return
      }
      let file = re
      updateCarArr.value[index]['status'] = 1
      const formData = new FormData();
      formData.append('file', file);
      const url = process.env.api + '/servers/uploadImage';
      const axios = require('axios')
      try {
        const response = await axios.post(url, formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        });
        console.log('文件上传成功:', response.data.data);
        updateCarArr.value[index]['status'] = 2
        updateCarArr.value[index]['value'] = response.data.data
      } catch (error) {
        console.log('文件上传失败')
        updateCarArr.value[index]['status'] = 3
      }
    }

    return {
      entityCode,
      updateInfo,
      updateCarArr,
      updataDataUrl,
      onreset,
      carDate,
      setInitValue,
      operateEvent,
      operateEventName,
      model,
      options,
      filterFn,
      setModel,
      mouseover,
      yeso,
      touch,
      indexTemp,
      serveIdArr,
      getImageId,
      getImageURL1,
      onReset,
      dicArray,
      getNumber,
      searchDic,
      dicOptions,
      fix,
      deleteImage,
      selectSingleImage
    };

  },
  mounted() {

  }
});
</script>
<style scoped></style>
